<?php

namespace app\common\model;


use app\common\exception\ApiException;
use app\common\lib\qiniuUpload;

class Images extends BaseModel {
    public function getUrlAttr($value, $data) {
        if ($data['from'] === 0) {
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            return $http_type . $_SERVER['HTTP_HOST'] . '/' . str_replace('\\', '\\\\', $value);
        } else {
            $cut = input('get.cut');
            if (empty($cut)) {
                return $value;
            }
            return $value . '?' . $cut;
        }
    }

    public function uploadToQiniu() {
        try {
            $image = qiniuUpload::image();
        } catch (\Exception $e) {
            throw new ApiException($e->getMessage(), 404);
        }
        return config('qiniu.image_url') . '/' . $image;
    }

    public function deleteImg($id) {
        $result = $this->where(['information_id' => $id])
            ->select();
        $arr    = [];
        foreach ($result as $item) {
            $url = str_replace(config('qiniu.image_url'), '', $item->url);
            array_push($arr, $url);
        }
        return qiniuUpload::delete($arr);
    }
}